const Token = appRequire('common/token');
const wxMini = appRequire('common/wx/wxMini');

const userModel = appRequire('models/user');
const loginLogModel = appRequire('models/loginLog');

// 导出对象，供其它模块调用
module.exports = {
    login,
    userInfo,
    shopUserInfo,
    updateUser,
    getPhoneNumber,
    isVip,
    loginByWxFwh,
};
async function getPhoneNumber(req, response) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['code'], response);
    if (checkResult == false) return;

    let result1 = await wxMini.decryptData(req)
    returnData.data = result1
    return response.json(returnData)
}

//更新用户信息
async function updateUser(req, response) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let result1 = Common.checkUrl(postData, ['uid'], response);
    if (result1 == false) return;

    let user = await userModel.user.update({
        avatarUrl: postData.avatarUrl,
        sex: postData.sex,
        nickName: postData.nickName,
        bgImageUrl: postData.bgImageUrl,
        signature: postData.signature,
        mobilePhoneNumber: postData.mobilePhoneNumber,
    }, {
        where: {
            objectId: postData.uid
        }
    })

    returnData.data = user
    return response.json(returnData)
}

//用户信息
async function shopUserInfo(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
    returnData.data = ""

    let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;

    let result4 = await userModel.user.findOne({
        where: {
            objectId: postData.uid,
        }
    })

    returnData.data = result4
    request.json(returnData)
}

//用户信息
async function userInfo(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
    returnData.data = ""

    let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;

    let result4 = await userModel.user.findOne({
        where: {
            objectId: postData.uid,
        }
    })

    returnData.data = result4
    request.json(returnData)
}

//用户信息
async function isVip(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let result1 = Common.checkUrl(postData, [], request);
    if (result1 == false) return;

    returnData.vipTime = 0
    if (postData.uid) {
        let result4 = await userModel.user.findOne({
            where: {
                objectId: postData.uid,
            }
        })
        result4 = Common.clone(result4)
        //console.log(result4)
        if (result4.vipTime) {
            returnData.data = true
            returnData.vipTime = result4.vipTime
            returnData.vipLink = "https://pan.baidu.com/s/1W3XAcRiBjoJrxIAlp0M1wg?pwd=tbok"
            returnData.vipLinkImage = "https://qiniu.jimuzhou.cloud/2023-08-23/2023823112014/fc6be040-4163-11ee-be80-17c704b514c3.png"
        } else {
            returnData.data = false
        }
    } else {
        returnData.data = false
    }
    request.json(returnData)
}

//微信服务号授权登陆
async function loginByWxFwh(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
    returnData.data = ""

    let result1 = Common.checkUrl(postData, ['openid'], request);
    if (result1 == false) return;

    let wcMiniId = postData.openid
    let result4 = await userModel.user.findOne({
        where: {
            wcMiniId: wcMiniId,
        }
    })

    if (result4) {
        returnData.data = result4
    } else {
        let params = {
            nickName: "微信用户" + wcMiniId.substring(24),
            avatarUrl: "https://qiniu.jimuzhou.cloud/common/touxiang.webp",
            objectId: sid.uuid()
        }
        params.wcMiniId = wcMiniId
        if ('' + postData.disabled) params.disabled = postData.disabled
        if ('' + postData.sex) params.sex = postData.sex
        if (postData.address) params.address = postData.address
        if (postData.mobilePhoneNumber) params.mobilePhoneNumber = postData.mobilePhoneNumber
        let result2 = await userModel.user.create(params)
        returnData.data = result2
    }

    // 记录登录日志
    if (returnData.data && returnData.data.objectId) {
        await loginLogModel.loginLog.create({
            objectId: sid.uuid(),
            userId: returnData.data.objectId,
            loginTime: new Date()
        }).catch(err => {
            console.log('登录日志记录失败:', err);
        });
    }

    if (returnData.data) returnData.token = await getToken(returnData.data)
    request.json(returnData)
}

//微信授权登陆
async function login(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
    returnData.data = ""

    let result1 = Common.checkUrl(postData, ['code'], request);
    if (result1 == false) return;

    let wxInfo = await wxMini.getMiniOpenId(req)
    let wcMiniId = wxInfo.openid

    let result4 = await userModel.user.findOne({
        where: {
            wcMiniId: wcMiniId,
        }
    })

    if (result4) {
        returnData.data = result4
    } else {
        let params = {
            nickName: "微信用户" + wcMiniId.substring(24),
            avatarUrl: "https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/images/08仙人掌团子.png",
            objectId: sid.uuid()
        }
        params.wcMiniId = wcMiniId
        if ('' + postData.disabled) params.disabled = postData.disabled
        if ('' + postData.sex) params.sex = postData.sex
        if (postData.address) params.address = postData.address
        if (postData.mobilePhoneNumber) params.mobilePhoneNumber = postData.mobilePhoneNumber
        let result2 = await userModel.user.create(params)
        returnData.data = result2
    }

    // 记录登录日志
    if (returnData.data && returnData.data.objectId) {
        await loginLogModel.loginLog.create({
            objectId: sid.uuid(),
            userId: returnData.data.objectId,
            loginTime: new Date()
        }).catch(err => {
            console.log('登录日志记录失败:', err);
        });
    }

    if (returnData.data) returnData.token = await getToken(returnData.data)
    request.json(returnData)
}

//返回token
async function getToken(result, TOKEN_EXPIRE_SENCOND = 36000000) {
    // 将admin的id保存在Token中
    let adminInfo = {
        uid: result.objectId,
    };

    // 生成Token
    let thisToken = Token.encrypt(adminInfo, TOKEN_EXPIRE_SENCOND);
    return thisToken
}
